﻿using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;

#pragma warning disable CS8618

namespace Vote.Project001.Core.Database
{
    public class DatabaseContext : DbContext
    {
        public static void InitDatabase()
        {
            using var db = new DatabaseContext();
#if DEBUG
            //db.Database.EnsureDeleted();
#endif

            db.Database.EnsureCreated();


            var list = db.Votes.Select(t => t.UserId).ToList();
            var p = new HashSet<string>();

            foreach (var s in list)
            {
                if(p.Contains(s))
                    continue;

                p.Add(s);
            }

        }

        private static void DatabaseMigrateVersion01(DatabaseContext db)
        {
            db.Database.ExecuteSqlRaw(
                "CREATE TABLE \"Setting\" (\r\n    \"Key\" NVARCHAR NOT NULL CONSTRAINT \"PK_Setting\" PRIMARY KEY,\r\n    \"Value\" NVARCHAR NOT NULL\r\n);");
        }


        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite(
                new SqliteConnectionStringBuilder() { DataSource = "database.db" }.ConnectionString);


            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Model.Vote>().Property(e => e.VoteTime).HasConversion<DateTimeToBinaryConverter>();

            modelBuilder.Entity<Model.Hero>().HasMany(h => h.Votes).WithOne();

            

            base.OnModelCreating(modelBuilder);
        }


        public virtual DbSet<Model.Hero> Heroes { get; set; }
        public virtual DbSet<Model.Vote> Votes { get; set; }
        public virtual DbSet<Model.User> Users { get; set; }
    }
}
